package club.zhilin.guli.service.cms.service.impl;

import club.zhilin.guli.service.cms.domain.Ad;
import club.zhilin.guli.service.cms.domain.vo.AdVO;
import club.zhilin.guli.service.cms.feign.OssFileService;
import club.zhilin.guli.service.cms.mapper.AdMapper;
import club.zhilin.guli.service.cms.service.IAdService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 广告推荐 服务实现类
 * </p>
 *
 * @author zhilin
 * @since 2022-02-22 16:00:09
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AdServiceImpl extends ServiceImpl<AdMapper, Ad> implements IAdService {

    private final OssFileService ossFileService;

    @Override
    public IPage<AdVO> selectPage(Long page, Long limit) {
        Page<AdVO> voPage = new Page<>(page, limit);
        List<AdVO> vos = this.baseMapper.selectPageList(voPage, new QueryWrapper<AdVO>().orderByAsc(Arrays.asList("a.type_id", "a.sort")));
        voPage.setRecords(vos);
        return voPage;
    }

    @Override
    public boolean removeAdImageId(String id) {
        Ad ad = baseMapper.selectById(id);
        if (ad != null) {
            String imagesUrl = ad.getImageUrl();
            if (StringUtils.isNotEmpty(imagesUrl)) {
                return ossFileService.remove(imagesUrl).isSuccess();
            }
        }
        return false;
    }

    @Override
    @Cacheable(value = "index", key = "'selectByAdTypeId'")
    public List<Ad> selectByAdTypeId(String id) {
        return baseMapper.selectList(new LambdaQueryWrapper<Ad>().orderByAsc(Arrays.asList(Ad::getSort, Ad::getId)).eq(Ad::getTypeId, id));
    }
}
